//
//  ViewController.m
//  btReaderTest
//
//  Created by Chenfan on 3/19/15.
//  Copyright (c) 2015 Chenfan. All rights reserved.
//

#import "ViewController.h"

#import <SRIDCardReader/SRIDCardReader.h>
#import <SRIDCardReader/SRBase64.h>

#import "SRIDReaderTestViewController.h"

#import <dlfcn.h>
//#import "ReadCertErrorInfo.h"

//以下接入信息请联系售前技术申请
#define APP_KEY         @"3D423EEA180F4AC0BD931F7923BD4EA5"
#define APP_SECRET      @"E0E6180B97B0437FAC9519187F5EBC85"
#define APP_PASSWORD    @"27FD4F85D4B34F3DACFF68EC9A4A9741"

//临时密钥，随时停，有效期截止2025年3月 31日，如需上线请申请正式的密钥信息：
//AppKey：3D423EEA180F4AC0BD931F7923BD4EA5
//AppSecret：E0E6180B97B0437FAC9519187F5EBC85
//AppPassword：27FD4F85D4B34F3DACFF68EC9A4A9741



@interface ViewController ()<CBCentralManagerDelegate,SRIDCardReaderDelegate, SRReaderControllerDelegate> {

    
	SRIDCardReader *sr;
	NSString *logicStr;
	CBCentralManager *manager;
	NSMutableArray *deviceList;
	NSMutableArray *nullList;
	int rowCount;
	ZSYPopoverListView *listView;

	CBPeripheral *currentDevice;

	NSString* currentName;
	NSData* currentImage;
	srSm4_context ctx;
	double recrodTime;

	NSMutableDictionary *infoDic;

	MPosCardReader *myMPosCardReader;
	NSString *saveDeviceName;
	BOOL isMposDevice;

	NSString *iccid;
    
    SRIDCardModel *_IDCardModel;
}

@property (strong, nonatomic) SRReaderController *readerController;

@property (nonatomic, retain) NSIndexPath *selectedIndexPath;
@end

@implementation ViewController

- (void)viewDidLoad {
	[super viewDidLoad];

	if (@available(iOS 13.0, *)) {
		UIUserInterfaceStyle mode = UITraitCollection.currentTraitCollection.userInterfaceStyle;
		if (mode == UIUserInterfaceStyleDark) {
			NSLog(@"深色模式");
			self.view.backgroundColor = [UIColor lightGrayColor];
			photoImageView.backgroundColor = [UIColor lightGrayColor];
		}
	}
    
	isMposDevice = false;
    //设置森锐读卡器
	sr = [SRIDCardReader initDevice];
	[sr setAppKey:APP_KEY];
	[sr setAppSecret:APP_SECRET];
	[sr setPassword:APP_PASSWORD];
    //扫描蓝牙设备控制器
	manager = [[CBCentralManager alloc]initWithDelegate:self queue:nil];
	listView = [[ZSYPopoverListView alloc] initWithFrame:CGRectMake(0, 0, 300, 300)];
	listView.titleName.text = @"阅读器列表";
	listView.datasource = self;
	listView.delegate = self;
    _logic.textColor = [UIColor blackColor];
	saveDeviceName = @"";

    //初始化SDK控制器
    self.readerController = [[SRReaderController alloc] initWithReader:sr manager:manager];
    _readerController.delegate = self;
    
    [_generatorIDCardBtn setEnabled:false];
}


-(void)showMessage:(NSString *)msg {
	dispatch_async(dispatch_get_main_queue(), ^{
		[readCardBtn setEnabled:true];
		[readCertBtn setEnabled:true];
		[bluetoothListBtn setEnabled:true];
		[readBank1Btn setEnabled:true];
		[readBank2Btn setEnabled:true];
		readerState.text=@"请点击读二代证按钮";

		UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"结果" message:msg preferredStyle:  UIAlertControllerStyleAlert];
		[alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
		                          //点击按钮的响应事件；
				  }]];
		//弹出提示框；
		[self presentViewController:alert animated:true completion:nil];
	});
}


-(IBAction) start:(id)Sender {//点击事件 读取二代身份证
	if (_readerLable.text.length < 1) {
		[self showMessage:@"请选择设备"];
		return;
	}
	readerState.text=@"开始读取身份证.......";
	name.text=@"";
	sex.text=@"";
	mz.text=@"";
	year.text=@"";
	mon.text=@"";
	day.text=@"";
	addr.text=@"";
	idNo.text=@"";
	org.text=@"";
	expDate.text=@"";
	timeConsuming.text=@"";
	photoImageView.image=nil;
	_logic.text=@"";
    _logic.textColor = [UIColor blackColor];
	[readCardBtn setEnabled:false];
	[readCertBtn setEnabled:false];
	[bluetoothListBtn setEnabled:false];
	[readBank1Btn setEnabled:false];
	[readBank2Btn setEnabled:false];
    [_generatorIDCardBtn setEnabled:false];
    
//    const jsonParam = {
//      idCardNumber:idCardNumber,
//      phoneNumber:phoneNumber,
//      innerSysNo:innerSysNo,
//      regionCode:regionCode,
//      regionName:regionName,
//      channelCode:channelCode,
//      channelName:channelName,
//      employeeId:employeeId,
//      cardTypeCode:cardTypeCode,
//      channelName:channelName,
//      cardTypeName:cardTypeName
//     }
    
    NSDictionary *parma = @{@"idCardNumber":@"111",
                            @"phoneNumber":@"13515555555",
                            @"innerSysNo":@"123",
                            @"regionCode":@"321",
                            @"regionName":@"3123",
                            @"channelCode":@"111",
                            @"channelName":@"222",
                            @"employeeId":@"44",
                            @"cardTypeCode":@"55",
                            @"cardTypeName":@"77",
    };
    [_readerController readIDCardWithPeripheral:currentDevice parameters:parma];
        
}


- (IBAction)readerList:(id)sender {
	deviceList=nil;
	manager.delegate=self;
    [listView show];
    _logic.text = @"搜索蓝牙设备..";
	[manager scanForPeripheralsWithServices:nil options:@{CBCentralManagerScanOptionAllowDuplicatesKey : @YES}];
}


- (IBAction)samReadCertClick:(id)sender {//只一体式设备才有此功能
	if (_readerLable.text.length < 1) {
		[self showMessage:@"请选择设备"];
		return;
	}
	int ret = [sr connectPeripheral:currentDevice withCBManager:manager withTimeout:10];
	if (ret == 0) {
		dispatch_async(dispatch_get_global_queue(0, 0), ^{
//            [sr readSAMCertInfo];
		});
	}else{
		[self showMessage:[NSString stringWithFormat:@"%d:设备连接失败", ret]];
	}
}

- (IBAction)readSIMCard:(id)sender {
	if (_readerLable.text.length < 1) {
		[self showMessage:@"请选择设备"];
		return;
	}

	[readCardBtn setEnabled:false];
	[readCertBtn setEnabled:false];
	[bluetoothListBtn setEnabled:false];
	[readBank1Btn setEnabled:false];
	[readBank2Btn setEnabled:false];
	int ret = [sr connectPeripheral:currentDevice withCBManager:manager withTimeout:10];
	if(ret == 0) {
		[sr readSimICCID:@""];
	}else{
		[self showMessage:[NSString stringWithFormat:@"%d:设备连接失败", ret]];
	}
}

-(void)connectReader:(CBPeripheral *)peripheral {
	recrodTime = [[NSDate date] timeIntervalSince1970];
	int ret = [sr connectPeripheral:peripheral withCBManager:manager withTimeout:5];
	NSLog(@"ret:%d",ret);
	if (ret == 0) {
		[sr readIDCardByJson:15];
	}else{
		[self showMessage:[NSString stringWithFormat:@"%d:设备连接失败", ret]];
	}

}

#pragma mark STIDCardReaderDelegate
/**
   读证失败回调
 */
- (void)SRfailedBack:(CBPeripheral *)peripheral withError:(NSError *)error
{
	if (error.code == -50) return;
//    endTime.text=[self getNowTime];
	NSLog(@"耗时:%f",([[NSDate date] timeIntervalSince1970]-recrodTime)*1000);
	dispatch_async(dispatch_get_main_queue(), ^{
		[readCardBtn setEnabled:true];
		[readCertBtn setEnabled:true];
		[bluetoothListBtn setEnabled:true];
		[readBank1Btn setEnabled:true];
		[readBank2Btn setEnabled:true];
		timeConsuming.text=[NSString stringWithFormat:@"%.0f毫秒",([[NSDate date] timeIntervalSince1970]-recrodTime)*1000];
		NSLog(@"%@",error.description);
		readerState.text = [NSString stringWithFormat:@"%ld", (long)error.code];
	});
	[self showMessage:[NSString stringWithFormat:@"%ld:%@",(long)error.code,[ReadCertErrorInfo getErrorInfo:(int)(error.code)]]];
	[sr closeReader];
	NSLog(@"读取失败：%ld",(long)error.code);
}

uint8_t decodeGetByte(char c)
{
    if (c == '+')
        return 62;
    else if (c == '/')
        return 63;
    else if (c <= '9')
        return (uint8_t)(c - '0' + 52);
    else if (c == '=')
        return 64;
    else if (c <= 'Z')
        return (uint8_t)(c - 'A');
    else if (c <= 'z')
        return (uint8_t)(c - 'a' + 26);
    return 64;
}


//解码
int base64decode(char *pDest, const char *pSrc, int srclen)
{
    uint8_t input[4];
    size_t i, index = 0;
    for (i = 0; i < srclen; i += 4)
    {
        //byte[0]
        input[0] = decodeGetByte(pSrc[i]);
        input[1] = decodeGetByte(pSrc[i + 1]);
        pDest[index++] = (input[0] << 2) + (input[1] >> 4);

        //byte[1]
        if (pSrc[i + 2] != '=')
        {
            input[2] = decodeGetByte(pSrc[i + 2]);
            pDest[index++] = ((input[1] & 0x0f) << 4) + (input[2] >> 2);
        }

        //byte[2]
        if (pSrc[i + 3] != '=')
        {
            input[3] = decodeGetByte(pSrc[i + 3]);
            pDest[index++] = ((input[2] & 0x03) << 6) + (input[3]);
        }
    }

    //null-terminator
    pDest[index] = 0;
    return index;
}

#pragma mark -获取json回调
- (void)idCardInfoJsonStr:(NSString *)jsonStr{
    [self handlerJson:jsonStr];
}
/*
   功能：返回读取结果的JSON字符串
   参数：JSON字符串
   返回值：无
 */
- (void)handlerJson:(NSString *)jsonStr {
	NSLog(@"idCardInfoJsonStr:读证成功");
	[sr closeReader];

	dispatch_async(dispatch_get_main_queue(), ^{
		timeConsuming.text=[NSString stringWithFormat:@"%.0f毫秒",([[NSDate date] timeIntervalSince1970]-recrodTime)*1000];
		//文字信息展示
		NSDictionary *certInfoDic = [self jsonStrToDic:jsonStr];
        
        SRIDCardModel *model = [[SRIDCardModel alloc] initWithDic:certInfoDic];
        _IDCardModel = model;
        
		name.text = [certInfoDic objectForKey:@"name"];
		sex.text = [certInfoDic objectForKey:@"gender"];
		mz.text = [certInfoDic objectForKey:@"nation"];
		year.text = [[certInfoDic objectForKey:@"birthday"] substringWithRange:NSMakeRange(0, 4)];
		mon.text = [[certInfoDic objectForKey:@"birthday"] substringWithRange:NSMakeRange(4, 2)];
		day.text = [[certInfoDic objectForKey:@"birthday"] substringWithRange:NSMakeRange(6, 2)];
		addr.text = [certInfoDic objectForKey:@"address"];
		idNo.text = [certInfoDic objectForKey:@"idNum"];
		org.text = [certInfoDic objectForKey:@"issueOrg"];
		expDate.text = [NSString stringWithFormat:@"%@-%@", [certInfoDic objectForKey:@"effectDate"], [certInfoDic objectForKey:@"expireDate"]];
        
        //港澳台字段
        passNum.text=[certInfoDic objectForKey:@"signCount"];
        passCard.text=[certInfoDic objectForKey:@"passNum"];
        
		//头像图片展示
		NSDictionary *infoDic = [self jsonStrToDic:jsonStr];
		NSString *imageStr = [infoDic objectForKey:@"photo"];
        
        uint8_t decodeData[50000];
        int decodeDataLen=base64decode(decodeData,[imageStr UTF8String],imageStr.length);
        
        NSData *photoData=[NSData dataWithBytes:decodeData length:decodeDataLen];
		UIImage* image=[UIImage imageWithData:photoData scale:1.0];
		NSLog(@"size:%f %f",image.size.width,image.size.height);
		((UIImageView*)self->photoImageView).image=image;
		[self->photoImageView setNeedsDisplay];

    

		[readCardBtn setEnabled:true];
		[readCertBtn setEnabled:true];
		[bluetoothListBtn setEnabled:true];
		[readBank1Btn setEnabled:true];
		[readBank2Btn setEnabled:true];
        [_generatorIDCardBtn setEnabled:true];
		readerState.text=@"请点击读二代证按钮";
	});

}


/*
   功能:代理方法,读取卡号时通过该方法返回结果
   参数:结果信息
   返回值:无
 */
- (void)ReadICCIDsuccessBack:(SRIDReadCardInfo*)peripheral withData:(id)data {
	NSLog(@"%d",[((NSNumber *)data) intValue]);
	iccid=peripheral.ICCID;
	[self performSelectorOnMainThread:@selector(showMessage:) withObject:[NSString stringWithFormat:@"%@:%@",data,peripheral.ICCID] waitUntilDone:NO];
	[sr closeReader];

}


#pragma mark -- CBCentralManagerDelegate
- (void)centralManagerDidUpdateState:(CBCentralManager *)central {
    switch (central.state) {
    case CBCentralManagerStatePoweredOn:
        break;
            
    case CBCentralManagerStatePoweredOff:
        [self showMessage:@"尚未打开蓝牙，请在设置中打开"];
        break;

    default:
        break;
    }
}

- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheraln advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI {
	//发现设备
	if(deviceList==nil) {
		deviceList=[NSMutableArray array];
	}
	if([deviceList containsObject:peripheraln] || peripheraln.name == nil) {
		return;
	}

	if (peripheraln.name.length != 0) {
		[deviceList addObject:peripheraln];
	}else{
		[nullList addObject:peripheraln];
	}

	rowCount=(int)[deviceList count];
	[listView.mainPopoverListView reloadData];
    
}


#pragma mark ZSYPopoverListDatasource
- (NSInteger)popoverListView:(ZSYPopoverListView *)tableView numberOfRowsInSection:(NSInteger)section {
	return rowCount;
}

- (UITableViewCell *)popoverListView:(ZSYPopoverListView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	static NSString *identifier = @"identifier";
	UITableView *myTableView = (UITableView *)tableView;
	UITableViewCell *cell = [tableView dequeueReusablePopoverCellWithIdentifier:identifier];
	if (nil == cell)
	{
		cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
	}
	if (self.selectedIndexPath && NSOrderedSame == [self.selectedIndexPath compare:indexPath])
	{
		cell.imageView.image = [UIImage imageNamed:@"fs_main_login_selected.png"];
	}
	else
	{
		cell.imageView.image = [UIImage imageNamed:@"fs_main_login_normal.png"];
	}
	if(indexPath.row < deviceList.count)
		cell.textLabel.text = ((CBPeripheral *)[deviceList objectAtIndex:indexPath.row]).name;
	return cell;

}


#pragma mark ZSYPopoverListDelegate
- (void)popoverListView:(ZSYPopoverListView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	self.selectedIndexPath = indexPath;
	UITableViewCell *cell = [tableView popoverCellForRowAtIndexPath:indexPath];
	cell.imageView.image = [UIImage imageNamed:@"fs_main_login_selected.png"];
	currentDevice=[deviceList objectAtIndex:indexPath.row];

	_readerLable.text = currentDevice.name;
	if ([currentDevice.name containsString:@"XGD"]) {
		isMposDevice = true;
	}else{
		isMposDevice = false;
	}

	[listView dismiss];
}


#pragma mark TOOL
//json字符串转字典
- (NSDictionary *)jsonStrToDic:(NSString *)jsonStr {
	if (jsonStr == nil) {
		return nil;
	}
    _logic.text = jsonStr;
	jsonStr =[jsonStr stringByTrimmingCharactersInSet:[NSCharacterSet controlCharacterSet]];//去除字符串里的垃圾字符
	NSData *jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
	NSError *err;
	NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
	                     options:NSJSONReadingMutableContainers
	                     error:&err];
	if(err)
	{
		NSLog(@"json解析失败：%@",err);
		return nil;
	}
	return dic;
}

#pragma mark - ReaderControllerDelegate

- (void)readFail:(CBPeripheral *)peripheral withError:(NSError *)error{
   
    [self showMessage:[NSString stringWithFormat:@"%ld:%@",(long)error.code,[ReadCertErrorInfo getErrorInfo:(int)(error.code)]]];
    [sr closeReader];
    NSLog(@"读取失败：%ld",(long)error.code);
}

- (void)readSuccessWithJsonStr:(NSString *)jsonStr{
    [self handlerJson:jsonStr];
}


//合成身份证图片按钮
- (IBAction)generateIDCardBtn:(id)sender{
    SRIDReaderTestViewController * testVC = [[SRIDReaderTestViewController alloc] init];
    testVC.readerController = self.readerController;
    testVC.IDCardModel = _IDCardModel;
    [self.navigationController pushViewController:testVC animated:YES];
}

@end
